package com.test.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.hikvision.netsdk.ExceptionCallBack;
import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.NET_DVR_DEVICEINFO_V30;
import com.hikvision.netsdk.NET_DVR_PICCFG_V30;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * Created by jy on 2018/5/9.
 */

public class HaiKangMonitorListActivity extends Activity {
    private final String TAG = "HaiKangMonitor";
    private int m_iLogID = -1; //登录者ID，登录成功以后后台返回
    private int m_iStartChan = 0; //通道开始
    private int m_iChanNum = 0; //通道总数
    private NET_DVR_DEVICEINFO_V30 m_oNetDvrDeviceInfoV30 = null;

    private String ip = "172.16.10.253";
    private int port = 8000;
    private String account = "admin";
    private String password = "admin12345";

    private ListView list_view;
    private Button btn;
    private AdapterHaiKangMonitorList adapter;
    private ArrayList<ChannelInfo> channelInfos = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_haikang_monitor_list);

        if (!initeSdk()) {
            this.finish();
            return;
        }

        list_view = (ListView) findViewById(R.id.list_view);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    /**
     * @fn initeSdk
     */
    private boolean initeSdk() {
        // init net sdk
        if (!HCNetSDK.getInstance().NET_DVR_Init()) {
            Log.e(TAG, "HCNetSDK init is failed!");
            return false;
        }
        HCNetSDK.getInstance().NET_DVR_SetLogToFile(3, "/mnt/sdcard/sdklog/",
                true);

        return true;
    }

    private void login() {
        try {
            if (m_iLogID < 0) {
                // login on the device
                m_iLogID = loginDevice();
                if (m_iLogID < 0) {
                    Log.e(TAG, "This device logins failed!");
                    return;
                } else {
                    System.out.println("m_iLogID=" + m_iLogID);
                }
                // get instance of exception callback and set
                ExceptionCallBack oexceptionCbf = getExceptiongCbf();
                if (oexceptionCbf == null) {
                    Log.e(TAG, "ExceptionCallBack object is failed!");
                    return;
                }

                if (!HCNetSDK.getInstance().NET_DVR_SetExceptionCallBack(
                        oexceptionCbf)) {
                    Log.e(TAG, "NET_DVR_SetExceptionCallBack is failed!");
                    return;
                }
                Log.i(TAG,
                        "Login sucess ****************************1***************************");
                getChannelNames();
            } else {
                // whether we have logout
                if (!HCNetSDK.getInstance().NET_DVR_Logout_V30(m_iLogID)) {
                    Log.e(TAG, " NET_DVR_Logout is failed!");
                    //if (!HCNetSDKJNAInstance.getInstance().NET_DVR_DeleteOpenEzvizUser(m_iLogID)) {
                    //		Log.e(TAG, " NET_DVR_DeleteOpenEzvizUser is failed!");
                    return;
                }
                m_iLogID = -1;
            }

        } catch (Exception err) {
            Log.e(TAG, "error: " + err.toString());
        }
    }

    /**
     * @return login ID
     * @fn loginDevice
     * @author zhangqing
     * @brief login on device
     * [in]
     * [out]
     */
    private int loginDevice() {
        int iLogID = -1;

        iLogID = loginNormalDevice();

        // iLogID = JNATest.TEST_EzvizLogin();
        // iLogID = loginEzvizDevice();

        return iLogID;
    }

    /**
     * @return login ID
     * @fn loginNormalDevice
     * @author zhuzhenlei
     * @brief login on device
     */
    private int loginNormalDevice() {
        // get instance
        m_oNetDvrDeviceInfoV30 = new NET_DVR_DEVICEINFO_V30();
        if (null == m_oNetDvrDeviceInfoV30) {
            Log.e(TAG, "HKNetDvrDeviceInfoV30 new is failed!");
            return -1;
        }
        // call NET_DVR_Login_v30 to login on, port 8000 as default
        int iLogID = HCNetSDK.getInstance().NET_DVR_Login_V30(ip, port,
                account, password, m_oNetDvrDeviceInfoV30);
        if (iLogID < 0) {
            Log.e(TAG, "NET_DVR_Login is failed!Err:"
                    + HCNetSDK.getInstance().NET_DVR_GetLastError());
            return -1;
        }
        if (m_oNetDvrDeviceInfoV30.byChanNum > 0) {
            m_iStartChan = m_oNetDvrDeviceInfoV30.byStartChan;
            m_iChanNum = m_oNetDvrDeviceInfoV30.byChanNum;
        } else if (m_oNetDvrDeviceInfoV30.byIPChanNum > 0) {
            m_iStartChan = m_oNetDvrDeviceInfoV30.byStartDChan;
            m_iChanNum = m_oNetDvrDeviceInfoV30.byIPChanNum
                    + m_oNetDvrDeviceInfoV30.byHighDChanNum * 256;
        }

        if (m_iChanNum > 1) {

        } else {

        }
        Log.i(TAG, "NET_DVR_Login is Successful!");

        return iLogID;
    }

    /**
     * @return exception instance
     * @fn getExceptiongCbf
     */
    private ExceptionCallBack getExceptiongCbf() {
        ExceptionCallBack oExceptionCbf = new ExceptionCallBack() {
            public void fExceptionCallBack(int iType, int iUserID, int iHandle) {
                System.out.println("recv exception, type:" + iType);
            }
        };
        return oExceptionCbf;
    }

    /**
     * @fn loginNormalDevice
     * 获取所有通道名称
     */
    private void getChannelNames() {
        for (int i = m_iStartChan; i < m_iChanNum; i++) {
            ChannelInfo channelInfo = new ChannelInfo();
            channelInfo.channelNumber = i;
            channelInfo.channelName = getOneChannelName(i);
            if(channelInfo.channelName != null && channelInfo.channelName.length() > 0)
                channelInfos.add(channelInfo);
        }
        adapter = new AdapterHaiKangMonitorList(this,channelInfos);
        list_view.setAdapter(adapter);

        list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ChannelInfo channelInfo = adapter.getItem(position);
                Intent intent = new Intent(HaiKangMonitorListActivity.this,HaiKangPlayActivity.class);
                intent.putExtra("m_iStartChan",channelInfo.channelNumber);
                intent.putExtra("m_iLogID",m_iLogID);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取当个通道名称
     */
    private String getOneChannelName(int channel) {
        String channelName = "";
        NET_DVR_PICCFG_V30 struPiccfg = new NET_DVR_PICCFG_V30();
        if (!HCNetSDK.getInstance().NET_DVR_GetDVRConfig(m_iLogID, HCNetSDK.NET_DVR_GET_PICCFG_V30, channel, struPiccfg)) {
            System.out.println("NET_DVR_GET_PICCFG_V30 faild!" + " err: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
        } else {
            try {
                int endPosition;
                for(endPosition=0;endPosition<struPiccfg.sChanName.length;endPosition++){
                    byte oneByte =  struPiccfg.sChanName[endPosition];
                    if(oneByte == 0){
                        break;
                    }
                }
                byte[] sChanName = new byte[endPosition];
                System.arraycopy(struPiccfg.sChanName, 0, sChanName, 0, endPosition);
                channelName = new String(sChanName, "GBK");
//                sChannalName = sChannalName.replace("大", "");
                Log.d(TAG, channelName);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println("NET_DVR_GET_PICCFG_V30 succ!" + new String(struPiccfg.sChanName));
        }
        return channelName;
    }
}
